package com.ln.prac.base.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * <pre>
 *  Java 代理
 * </pre>
 *
 * @Author zhangj
 * @Date 2022/6/18 23:07
 */
public class CglibTest {

    static class TranStation  {
        public void sell() {
            System.out.println("火车站卖票");
        }
    }

    static class ProxyFactory implements MethodInterceptor {
        private TranStation target = new TranStation();
        public TranStation getProxyObject() {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(target.getClass());
            enhancer.setCallback(this);
            TranStation obj = (TranStation) enhancer.create();
            return obj;
        }


        @Override
        public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
            System.out.println("代理...");
            return methodProxy.invokeSuper(o, args);
        }
    }

    public static void main(String[] args) {
        ProxyFactory fac = new ProxyFactory();
        TranStation proxyObject = fac.getProxyObject();
        proxyObject.sell();
    }


}
